<template>
  <div class="img-popupbox">
    <img class="imgBox" ref="img" :src="imgUrl" />
    <div class="txtBox">
      <span @click="$emit('close')">取消</span>
      <span @click="success">完成</span>
    </div>
  </div>
</template>

<script>
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";
import { updateUserPhoto } from "@/api/axios";
export default {
  name: "img-popupbox",
  data() {
    return {
      cropper: null,
    };
  },
  props: {
    imgUrl: {
      type: [String, Object],
      required: true,
    },
  },
  methods: {
    success() {
      // 基于服务端的裁切使用 getData 方法获取裁切参数
      // console.log(this.cropper.getData())
      // 纯客户端的裁切使用 getCroppedCanvas 获取裁切的文件对象===pc端兼容性不好
      this.cropper.getCroppedCanvas().toBlob((blob) => {
        this.upImgDataFun(blob);
      });
    },
    async upImgDataFun(data) {
      this.$toast.loading({
        message: "修改中...",
        forbidClick: true,
      });
      try {
        // 使用formDate传参
        let formDate = new FormData();
        formDate.append("photo", data);
        //  发送请求
        const { data: res } = await updateUserPhoto(formDate);
        console.log(res, 666);
        this.$emit("close", res.data.photo);
        this.$toast.success("修改成功");
      } catch (err) {
        console.log(err);
        this.$toast.fail("修改失败，稍后再试");
      }
    },
  },
  mounted() {
    //   获取img的实例对象
    const image = this.$refs.img;
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: "move",
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true,
    });
  },
  created() {},
};
</script>

<style lang='less' scoped>
.img-popupbox {
  height: 100%;
  background-color: #000;
  .imgBox {
    max-width: 100%;
    width: 100%;
    display: block;
  }
  .txtBox {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    span{
        font-size: 30px;
        padding: 20px;
        margin: 20px;
    }
  }
}
</style>